"""
线损模块路由
实现RTU线损查询相关的API接口
"""
from datetime import date

from fastapi import APIRouter, Depends, Query

from app.common.auth import require_analytics_view
from app.common.common import DbDep, AuditLogDep, PaginationDep
from app.schemas.line_loss_schemas import (
	RtuLineLossListRequest,
	RtuLineLossListResponse,
	RtuLineLossDetailResponse,
	LineLossOverviewResponse
)
from app.schemas.user_schemas import UserInDB
from app.service.line_loss_service import LineLossService
from common.exceptions import BizException
from common.logger import create_logger
from common.response import ApiResponse

logger = create_logger("line_loss_router")

router = APIRouter(prefix="/device/line-loss", tags=["线损管理"])


@router.get(
	"/rtu-list",
	response_model=ApiResponse[RtuLineLossListResponse],
	summary="RTU线损列表",
	description="分页查询RTU线损数据，支持按日期、RTU序列号、台区ID筛选"
)
async def get_rtu_line_loss_list(
		db: DbDep,
		page: PaginationDep,
		_audit: AuditLogDep,
		request: RtuLineLossListRequest = Depends(),
		_: UserInDB = Depends(require_analytics_view),
) -> ApiResponse[RtuLineLossListResponse]:
	"""
	RTU线损列表查询

	参数:
	- request: RTU线损列表查询请求参数
	  - start_date: 开始日期
	  - end_date: 结束日期
	  - serial_no: RTU序列号（可选）
	  - station_id: 台区ID（可选）
	- page: 页码
	- size: 每页大小

	返回:
	- ApiResponse[RtuLineLossListResponse]: 包含总数、分页信息和RTU线损列表数据
	"""
	try:
		result = await LineLossService.get_rtu_line_loss_list(db, request, page)
		logger.info(f"RTU线损列表查询成功，返回 {len(result.items)} 条记录")
		return ApiResponse.success(data=result, message="RTU线损列表查询成功")

	except BizException as e:
		return ApiResponse.error(
			message=e.error_message,
			code=e.error_code.http_code,
			error_code=e.error_code.biz_code
		)
	except Exception as e:
		logger.error(f"RTU线损列表查询系统异常: {e}", exc_info=True)
		return ApiResponse.error(message=f"RTU线损列表查询失败: {str(e)}", code=500)


@router.get(
	"/rtu/{rtu_id}/detail",
	response_model=ApiResponse[RtuLineLossDetailResponse],
	summary="RTU线损详情",
	description="获取指定RTU在某日的线损详情，包括下属电表用电量明细"
)
async def get_rtu_line_loss_detail(
		db: DbDep,
		_audit: AuditLogDep,
		rtu_id: int,
		calc_date: date = Query(..., description="计算日期"),
		_: UserInDB = Depends(require_analytics_view),
) -> ApiResponse[RtuLineLossDetailResponse]:
	"""
	RTU线损详情查询

	参数:
	- rtu_id: RTU设备ID
	- calc_date: 计算日期

	返回:
	- ApiResponse[RtuLineLossDetailResponse]: RTU线损详情和下属电表用电量明细
	"""
	try:

		result = await LineLossService.get_rtu_line_loss_detail(db, rtu_id, calc_date)
		logger.info(f"RTU线损详情查询成功")
		return ApiResponse.success(data=result, message="RTU线损详情查询成功")

	except BizException as e:
		return ApiResponse.error(
			message=e.error_message,
			code=e.error_code.http_code,
			error_code=e.error_code.biz_code
		)
	except Exception as e:
		logger.error(f"RTU线损详情查询系统异常: {e}", exc_info=True)
		return ApiResponse.error(message=f"RTU线损详情查询失败: {str(e)}", code=500)


@router.get(
	"/overview",
	response_model=ApiResponse[LineLossOverviewResponse],
	summary="线损概览",
	description="获取总线损率和总损耗电量，默认为昨天的数据"
)
async def get_line_loss_overview(
		db: DbDep,
		_audit: AuditLogDep,
		calc_date: date | None = Query(None, description="计算日期，默认为昨天"),
		current_user: UserInDB = Depends(require_analytics_view),
) -> ApiResponse[LineLossOverviewResponse]:
	"""
	线损概览查询

	参数:
	- calc_date: 计算日期（可选，默认为昨天）

	返回:
	- ApiResponse[LineLossOverviewResponse]: 总线损率和总损耗电量
	"""
	try:
		logger.info(f"用户 {current_user.username} 请求线损概览数据")

		result = await LineLossService.get_line_loss_overview(db, calc_date)
		logger.info(f"线损概览查询成功")
		return ApiResponse.success(data=result, message="线损概览查询成功")

	except BizException as e:
		return ApiResponse.error(
			message=e.error_message,
			code=e.error_code.http_code,
			error_code=e.error_code.biz_code
		)
	except Exception as e:
		logger.error(f"线损概览查询系统异常: {e}", exc_info=True)
		return ApiResponse.error(message=f"线损概览查询失败: {str(e)}", code=500)
